////////////////////////////////////////////////////////////////////////////////
// YAHWS : Yet Another HTTP Web Server                                        //
// main.cpp                                                                   //
// Main file of the program                                                   //
// Florent Bacci, Julien Grall                                                //
////////////////////////////////////////////////////////////////////////////////

#if defined (linux)

#include <iostream>
#include <string>
#include <sstream>

#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>

#include "csocket.h"

#else
#error System not supported, please use a compatible OS
#endif

using namespace std;

static void* proceed_request(void* request);

int main(/*int argc, char* argv[]*/) {
	//Multithreading initialization
	pthread_t thread_number;
	csocket serv_socket;
	if (!serv_socket.cserver_TCP(80, 10))
	{
		cout << "Erreur dans l'initialisation" << endl;
		abort();
	}
	cout << "Serveur initialisé" << endl;
	
	while(1) {
		csocket *link_socket;
		link_socket = serv_socket.caccept();
		if (link_socket != NULL)
		{
			cout << "Nouvelle connexion" << endl;
			pthread_create (&thread_number, NULL, proceed_request, link_socket);
		}
		else
		{
			cout << "Connexion avortée" << endl;
		}
	}
	
	return 0;
}

static void* proceed_request(void* request)
{
	//Part that will treat a request
	csocket *link_socket = (csocket*)request;

	cout << "Client connecté" << endl;
	
	string message = "";
	
	(*link_socket).creceive(&message);

	//Responding 404 (test)
	string WebPage = "<HTML><BODY><H2>ERROR 404</H2></BODY></HTML>";
	WebPage = WebPage + (char)13 + (char)10;
	string Response = "HTTP/1.1 404 NOT FOUND\r\n";
	Response = Response + "Content-Type: text/html\r\n";
	stringstream size;
	size << WebPage.size();
	Response = Response + "Content-Lenght: " + size.str() + "\r\n\r\n";
	Response = Response + (char)13 + (char)10;

	if (!(*link_socket).csend(Response))
	{
		cout << "Send error in Header";
	}
	if (!(*link_socket).csend(WebPage))
	{
		cout << "Send error in WebPage";
	}
	
	if(!(*link_socket).cclose())
	{
		cout << "Erreur dans la fermeture du socket" << endl;
	}
	cout << "Client terminé" << endl;
	
	delete link_socket;
	
	return NULL;
}
